import requests
import json
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest

class NotificationService:
    def __init__(self, config):
        self.config = config
        # 初始化阿里云短信服务
        self.sms_client = AcsClient(
            self.config['aliyun']['access_key_id'],
            self.config['aliyun']['access_key_secret'],
            'cn-hangzhou'
        )
        
    def send_sms(self, phone_number, content):
        """发送短信通知"""
        request = CommonRequest()
        request.set_accept_format('json')
        request.set_domain('dysmsapi.aliyuncs.com')
        request.set_method('POST')
        request.set_protocol_type('https')
        request.set_version('2017-05-25')
        request.set_action_name('SendSms')
        
        request.add_query_param('PhoneNumbers', phone_number)
        request.add_query_param('SignName', self.config['aliyun']['sign_name'])
        request.add_query_param('TemplateCode', self.config['aliyun']['template_code'])
        
        # 组装短信内容
        template_param = {"strategy": content}
        request.add_query_param('TemplateParam', json.dumps(template_param))
        
        response = self.sms_client.do_action_with_exception(request)
        return json.loads(response)
        
    def send_wechat(self, user_id, content):
        """发送微信通知"""
        # 企业微信或微信公众号API
        url = "https://qyapi.weixin.qq.com/cgi-bin/message/send"
        
        # 获取访问令牌
        token_url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={self.config['wechat']['corp_id']}&corpsecret={self.config['wechat']['corp_secret']}"
        token_response = requests.get(token_url)
        access_token = token_response.json()['access_token']
        
        # 组装消息内容
        data = {
            "touser": user_id,
            "msgtype": "text",
            "agentid": self.config['wechat']['agent_id'],
            "text": {
                "content": content
            }
        }
        
        # 发送请求
        response = requests.post(
            f"{url}?access_token={access_token}",
            data=json.dumps(data)
        )
        
        return response.json()
        
    def send_email(self, email, subject, content):
        """发送邮件通知"""
        msg = MIMEMultipart()
        msg['From'] = self.config['email']['sender']
        msg['To'] = email
        msg['Subject'] = subject
        
        body = MIMEText(content, 'html')
        msg.attach(body)
        
        try:
            smtp_server = smtplib.SMTP(self.config['email']['smtp_server'], self.config['email']['smtp_port'])
            smtp_server.ehlo()
            smtp_server.starttls()
            smtp_server.login(self.config['email']['username'], self.config['email']['password'])
            text = msg.as_string()
            smtp_server.sendmail(self.config['email']['sender'], email, text)
            smtp_server.quit()
            return {"status": "success"}
        except Exception as e:
            return {"status": "error", "message": str(e)}
    
    def format_strategy_message(self, stock_code, stock_name, strategy):
        """格式化策略消息"""
        action_emoji = "🔴买入" if strategy['action'] == 'buy' else "🔵卖出" if strategy['action'] == 'sell' else "⚪观望"
        confidence_text = "高" if strategy['confidence'] == 'high' else "中" if strategy['confidence'] == 'medium' else "低"
        
        timeframe_text = "短期(1-5天)" if strategy['timeframe'] == 'short' else \
                         "中期(1-3月)" if strategy['timeframe'] == 'medium' else "长期(6个月以上)"
        
        message = f"""
        📊 股票策略推送 📊
        
        股票: {stock_name}({stock_code})
        建议: {action_emoji}
        周期: {timeframe_text}
        置信度: {confidence_text}
        
        依据: {strategy['reasoning']}
        
        ⏰ {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
        """
        
        return message.strip() 